package com.niji.littly_donkey_android.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.BankCardAdapter;
import com.niji.littly_donkey_android.bean.BankCard;
import com.niji.littly_donkey_android.bean.JsonBean;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import com.xuexiang.xui.widget.button.switchbutton.SwitchButton;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddlBankCardActivity extends BaseActivity {
    private final static String TAG = "AddlBankCardActivity";

    private static Integer defalut = 1;

    private Button add_bank_card_return;

    private Button set_default_bank;

    private Button set_default_bank_left;

    private EditText add_bank_bank_user;

    private EditText add_bank_bank_idCard;

    private EditText add_bank_bank_number;

    private EditText add_bank_bank_name;

    private Button add_bank_submit;

    private Thread thread;

    private RelativeLayout add_bank_city;

    private TextView add_bank_province_text;

    private TextView add_bank_city_text;

    private RelativeLayout add_bank_province;

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static boolean isLoaded = false;


    private RelativeLayout set_default_bank_bj;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_bank_card_activity);
        init();
        addBankCardReturn();
//        setDefaultBank();
        addBankSubmit();
        addBankProvince();
        addBankCity();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.add_bank_card_activity;

    }
    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }


    private void addBankCity() {
        add_bank_city = findViewById(R.id.add_bank_city);
        add_bank_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLoaded) {
                    showProvinceView();
                } else {
                    Toast.makeText(AddlBankCardActivity.this, "请等待数据加载", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void addBankProvince() {
        add_bank_province = findViewById(R.id.add_bank_province);
        add_bank_province.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isLoaded) {
                    showProvinceView();
                } else {
                    Toast.makeText(AddlBankCardActivity.this, "请等待数据加载", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void init() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 子线程中解析省市区数据
                initJsonData();
            }
        });
        thread.start();
    }

    /**
     * 添加银行卡提交事件
     */
    private void addBankSubmit() {
        add_bank_bank_user = findViewById(R.id.add_bank_bank_user);
        add_bank_bank_idCard = findViewById(R.id.add_bank_bank_idCard);
        add_bank_bank_number = findViewById(R.id.add_bank_bank_number);
        add_bank_bank_name = findViewById(R.id.add_bank_bank_name);
        add_bank_submit = findViewById(R.id.add_bank_submit);
        SwitchButton add_bank_default = findViewById(R.id.add_bank_default);
        add_bank_default.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if (isChecked){
                   defalut = 2;
               }else {
                   defalut = 1;
               }
            }
        });
        add_bank_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String province = add_bank_province_text.getText().toString().trim();
                String city = add_bank_city_text.getText().toString().trim();
                String name = add_bank_bank_user.getText().toString().trim();
                String idCard = add_bank_bank_idCard.getText().toString().trim();
                String bankCard = add_bank_bank_number.getText().toString().trim();
                String bankName = add_bank_bank_name.getText().toString().trim();
                if(province.equals("")){
                    Toast.makeText(AddlBankCardActivity.this,"请选择省市",Toast.LENGTH_SHORT).show();
                }else if("".equals(city)){
                    Toast.makeText(AddlBankCardActivity.this,"请选择省市",Toast.LENGTH_SHORT).show();
                }else if("".equals(name)){
                    Toast.makeText(AddlBankCardActivity.this,"持卡人姓名不能为空",Toast.LENGTH_SHORT).show();
                }else if("".equals(idCard) || !IdcardValidatorUtil.isIdcard(idCard)){
                    Toast.makeText(AddlBankCardActivity.this,"身份证号不能为空或身份证格式不对",Toast.LENGTH_SHORT).show();
                }else if("".equals(bankCard) || !BankCardUtil.checkBankCard(bankCard)){
                    Toast.makeText(AddlBankCardActivity.this,"银行卡卡号不能为空或银行卡卡号格式不对",Toast.LENGTH_SHORT).show();
                }else if("".equals(bankName)){
                    Toast.makeText(AddlBankCardActivity.this,"银行名称不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    String url = UrlUtil.URL + "/commission/add/bank/card?name=" + name + "&id_card=" + idCard + "&bank_card=" + bankCard + "&bank_name=" + bankName + "&province=" + province + "&city=" + city + "&is_default=" + defalut;
                    RequestQueue requestQueue= Volley.newRequestQueue(AddlBankCardActivity.this);
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                Map<String, Object> map = JsonUtil.jsonToMap(s);
                                Integer code = (Integer) map.get("code");
                                if (code == 0) {
                                    String message = (String) map.get("data");
                                    Toast.makeText(AddlBankCardActivity.this, message, Toast.LENGTH_LONG).show();
                                    overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                                    finish();
                                } else if(code == -1){
                                    Toast.makeText(AddlBankCardActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(AddlBankCardActivity.this, GetPhoneCodeActivity.class);
                                    intent.putExtra("loginCode","-1");
                                    startActivity(intent);
                                    finish();
                                }else {
                                    String message = (String) map.get("data");
                                    Toast.makeText(AddlBankCardActivity.this, message, Toast.LENGTH_SHORT).show();
                                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                    finish();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
//                            RelativeLayout bank_card_loading = findViewById(R.id.bank_card_loading);
//                            RelativeLayout bank_card_main = findViewById(R.id.bank_card_main);
//                            bank_card_main.setVisibility(View.VISIBLE);
//                            bank_card_loading.setVisibility(View.INVISIBLE);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, volleyError.getMessage(), volleyError);
                        }
                    }) {
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            String sesseionid = new ConnectViaSession(AddlBankCardActivity.this).GetSession();
                            if (!sesseionid.equals("")) {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("cookie", sesseionid);
                                return headers;
                            } else {
                                return super.getHeaders();
                            }
                        }
                    };

                    requestQueue.add(stringRequest);
                }


            }
        });

    }


    /**
     * 返回事件
     */
    private void addBankCardReturn() {
        add_bank_card_return = findViewById(R.id.add_bank_card_return);
        add_bank_card_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();
            }
        });
    }



    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
    private void showProvinceView() {// 弹出选择器
        add_bank_province_text = findViewById(R.id.add_bank_province_text);
        add_bank_city_text = findViewById(R.id.add_bank_city_text);

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                add_bank_province_text.setText(opt1tx);
                add_bank_city_text.setText(opt2tx);
                return false;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(AddlBankCardActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(AddlBankCardActivity.this, "数据加载成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(AddlBankCardActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}
